package dao

import (
	"fmt"
	"log"
	"time"
)

type User struct { //t_users
	Id         int64     `gorm:"primaryKey" json:"id"`
	Username   string    `json:"username"`
	Password   string    `json:"password"`
	Status     int       `json:"status"` // 0 正常状态， 1删除
	Createtime time.Time `json:"createtime"`
}

type UserDao struct{}

func (u *UserDao) QueryAllUser() (users []*User) {
	result := gormDB.Find(&users)
	fmt.Println(result.RowsAffected)
	if result.RowsAffected == 0 {
		return nil
	}
	return
}
func (u *UserDao) GetUser(argUser *User) (user *User) {
	user, err = UserCache.GetUserCacheByUsername(argUser)
	if err == nil {
		log.Println("缓存命中")
		return user
	} else {
		log.Println("no缓存命中", err, user)
	}

	user = &User{}
	result := gormDB.Find(user, argUser)
	fmt.Println(result.RowsAffected) //受影响的行数
	if result.RowsAffected == 0 {
		return nil
	}

	err := UserCache.AddUserCache(user)
	if err != nil {
		log.Println("get缓存添加失败", err)
	}
	return
}
func (u *UserDao) InsertUser(argUser *User) bool {

	argUser.Createtime = time.Now()
	result := gormDB.Create(argUser)
	fmt.Println(result.RowsAffected)

	if result.RowsAffected == 0 {
		return false
	}
	return true
}
func (u *UserDao) UpdateUser(argUser *User) bool {
	result := gormDB.Updates(argUser)
	fmt.Println(result.RowsAffected)
	if result.RowsAffected == 0 {
		return false
	}

	err := UserCache.DelUserCacheByUsername(argUser)
	if err != nil {
		log.Println("update 清理缓存失败 应该添加队列删除 或者。。高并发有概率发生数据不一致的现象 。或者确实没有", err)
	}

	return true
}
func (u *UserDao) DelUser(argUser *User) bool {
	result := gormDB.Delete(argUser)
	fmt.Println(result.RowsAffected)
	if result.RowsAffected == 0 {
		return false
	}

	err := UserCache.DelUserCacheByUsername(argUser)
	if err != nil {
		log.Println("delete 清理缓存失败 应该添加队列删除 或者。。高并发有概率发生数据不一致的现象  或者。确实没有", err)
	}

	return true
}
